from urllib.parse import urlparse
import os
import requests
from datetime import datetime,timedelta
from config.template import template_config
from https.httputils import DataManager
from pathlib import Path

class UploadPaths:
    def __init__(self):
        self.paths = {
            'png': 'static/upload/png',
            'gif': 'static/upload/gif',
            'music': 'static/upload/music',
            'out': 'static/video_output/template',
            'temp': 'static/upload/temp'
        }

    def get_path(self, file_type):
        return self.paths.get(file_type)


def upload_file(path_url, upload_folder):
    try:
        parsed_url = urlparse(path_url)
        file_path = parsed_url.path
        response = requests.get(path_url)
        if response.status_code == 200:
            filename = os.path.basename(path_url)
            current_time = datetime.now().strftime("%Y%m%d%H%M%S")
            file_path = os.path.join(upload_folder, current_time + "_" + filename)
            with open(file_path, 'wb') as f:
                f.write(response.content)
            print(f">>>下载：{file_path} 完成")
        return file_path.replace('\\', '/')
    except Exception as e:
        print(f">>>下载：{file_path} 失败，重试中....")
        upload_file(path_url, upload_folder)


def delete_file(file_path):
    """尝试删除文件，并处理可能的错误"""
    try:
        file_path.unlink()
    except Exception as e:
        pass  # 明确忽略异常


def list_files_temp_to_delete(val, cwd):
    upload_paths = UploadPaths()
    folder_path = Path(upload_paths.get_path(val))
    # 获取昨天的日期
    yesterday = datetime.now() - timedelta(days=1)
    # 格式化日期为所需的字符串格式
    yesterday_str = yesterday.strftime('%Y%m%d')
    # 删除指定文件夹下的所有文件
    for file_path in folder_path.iterdir():
        if file_path.is_file() and yesterday_str in file_path.name:
            delete_file(file_path)

    # 删除当前工作目录下的所有.mp3文件
    cwd_path = Path(cwd)
    for file_path in cwd_path.glob('*.mp3'):
        delete_file(file_path)

    print(">>>Delete Temp File successful")


# 保存文件服务器返回地址
def save_file_path_to_json(json_data):
    try:
        data_manager = DataManager(api_url=template_config.upload_address)
        response_data = data_manager.send_post2(json_data)
        print(f">>>Video data save successful:\n{response_data}")
    except Exception as e:
        print(f"<<<Video data save Error:\n{e}")
        raise

    return response_data
